package org.ymf.security;

import org.apache.tomcat.util.codec.binary.Base64;
import org.layuiframework.stereotype.security.bean.AbstractKeyPair;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

@Component
public class KeyPair extends AbstractKeyPair {

    private String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKY09eWbK+WI2yd/DlBI5GS6Ni08zzEdty/T4sFt74HSBdnySnDnVWOmyN1ZyEHjBuy5vfoJZ3oZQzjdNYJQKvQPN0Qp72ySixPM0WpKiNa81UuPtxeYo772UxgmqXabte7fqzR4zZtNCh06U/knjyPr9SX//SDFQcNK/4UGvQKwIDAQAB";
    private String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMpjT15Zsr5YjbJ38OUEjkZLo2LTzPMR23L9PiwW3vgdIF2fJKcOdVY6bI3VnIQeMG7Lm9+glnehlDON01glAq9A83RCnvbJKLE8zRakqI1rzVS4+3F5ijvvZTGCapdpu17t+rNHjNm00KHTpT+SePI+v1Jf/9IMVBw0r/hQa9ArAgMBAAECgYEAmez2DFhELajD/Bxkxom0e5pDZYKYubW3Jbmdc4Lhier9FrdW9Qd2DmLY9Pal14XuaBXLM0W7qrjlMmCHgN6FLtF0xd5oTx4aZ6KWH99l2UoUgaJ0WByQgNk1Y1GhrZLccLUfI06+EMswx5vwTHpOtyalwGZ8UBOKd1rPzKt3FCECQQD6V8b8/KPb2PDgAUDLpm9Td+6uXICpOl1tHtqJ9gNFo37cB9/V05KA9Oe0Qy9FteDUcV+ec5zsUxsJJDjVZGSdAkEAzvYdjLncESc1f/VsrLTTvw9tR0HCkHUwx3nxnGmnPoXupf13MQs7Hb6pzpAkVma8QMJ6sfN4M8ZbWiTta8QZZwJBANOj06FbQHgDLphh1tKUUTeCg/E6WLc4lXVECUNrDRcZgo0nxw7xf8Cvyxb1WYiYm4tekZTWbsrH82pGCho1dm0CQQDFQP/zA6YC10r/dWwpw4NZw5tU4hFN29QtG0Wz3WMgjUhi/oyeuuSSOgngLbPkgbCFTJbiinoTZsfkx/Nd1h6bAkBcyP7pnbJuJbxhohX+nyDtC8hjx14wRKhmZ4qm5mw2qzIOlP/Fy8CcPIZiO4KwjTT7p/Vsayum6SqdJyYWgtIR";

    @Override
    public String getPublicKey() {
        return publicKey;
    }

    @Override
    public String getPrivateKey() {
        return privateKey;
    }

    public static void main(String[] args) throws Exception{
        KeyPair keyPair = new KeyPair();
        // 密码
        String presentedPassword = "123456";
        System.out.println("原始密码  presentedPassword = " + presentedPassword);
        byte[] decoded = Base64.decodeBase64(keyPair.getPublicKey());
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        // 前端加密后的密码
        String webPassword = Base64.encodeBase64String(cipher.doFinal(presentedPassword.getBytes("UTF-8")));
        System.out.println("前端加密后  webPassword = " + webPassword);
        PasswordEncoder encode  = new BCryptPasswordEncoder();
        // 数据库里面保存的密码
        String databasePassword = encode.encode(presentedPassword);
        System.out.println("数据库保存  databasePassword = " + databasePassword);
    }
}